<template>
  <div class="message-reminder">
    <el-card class="reminder-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-input
              v-model="searchQuery"
              placeholder="搜索提醒规则名称"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
              style="width: 200px"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleCreate">
              <el-icon><Plus /></el-icon>新建提醒规则
            </el-button>
          </div>
          <div class="header-right">
            <el-radio-group v-model="statusFilter" @change="handleSearch">
              <el-radio-button label="">全部</el-radio-button>
              <el-radio-button label="active">启用</el-radio-button>
              <el-radio-button label="inactive">停用</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </template>

      <el-table
        :data="reminderList"
        border
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="name" label="规则名称" min-width="150" />
        <el-table-column prop="type" label="提醒类型" width="120">
          <template #default="scope">
            <el-tag :type="getReminderTypeTag(scope.row.type)">
              {{ getReminderTypeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="condition" label="触发条件" min-width="200">
          <template #default="scope">
            <div class="condition-text">
              {{ formatCondition(scope.row.condition) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="channels" label="提醒方式" width="200">
          <template #default="scope">
            <el-tag
              v-for="channel in scope.row.channels"
              :key="channel"
              class="channel-tag"
              :type="getChannelType(channel)"
            >
              {{ getChannelLabel(channel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="'active'"
              :inactive-value="'inactive'"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              type="primary"
              link
              @click="handleViewRecords(scope.row)"
            >记录</el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 提醒规则表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '新建提醒规则' : '编辑提醒规则'"
      width="700px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="提醒类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择提醒类型">
            <el-option
              v-for="type in reminderTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="触发条件" prop="condition">
          <el-form-item
            v-for="(condition, index) in form.conditions"
            :key="index"
            :prop="'conditions.' + index + '.value'"
            :rules="{ required: true, message: '请输入触发条件', trigger: 'blur' }"
          >
            <div class="condition-item">
              <el-select
                v-model="condition.field"
                placeholder="选择字段"
                style="width: 150px"
              >
                <el-option
                  v-for="field in conditionFields"
                  :key="field.value"
                  :label="field.label"
                  :value="field.value"
                />
              </el-select>
              <el-select
                v-model="condition.operator"
                placeholder="选择操作符"
                style="width: 120px"
              >
                <el-option
                  v-for="op in operators"
                  :key="op.value"
                  :label="op.label"
                  :value="op.value"
                />
              </el-select>
              <el-input
                v-model="condition.value"
                placeholder="输入值"
                style="width: 200px"
              />
              <el-button
                type="danger"
                link
                @click="removeCondition(index)"
                v-if="form.conditions.length > 1"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </el-form-item>
          <el-button type="primary" link @click="addCondition">
            <el-icon><Plus /></el-icon>添加条件
          </el-button>
        </el-form-item>
        <el-form-item label="提醒方式" prop="channels">
          <el-checkbox-group v-model="form.channels">
            <el-checkbox
              v-for="channel in reminderChannels"
              :key="channel.value"
              :label="channel.value"
            >
              {{ channel.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="提醒时间" prop="timing">
          <el-radio-group v-model="form.timing.type">
            <el-radio label="immediate">立即提醒</el-radio>
            <el-radio label="delay">延迟提醒</el-radio>
            <el-radio label="schedule">定时提醒</el-radio>
          </el-radio-group>
          <div class="timing-settings" v-if="form.timing.type !== 'immediate'">
            <template v-if="form.timing.type === 'delay'">
              <el-input-number
                v-model="form.timing.delay"
                :min="1"
                :max="1440"
                style="width: 120px"
              />
              <el-select v-model="form.timing.unit" style="width: 100px">
                <el-option label="分钟" value="minutes" />
                <el-option label="小时" value="hours" />
                <el-option label="天" value="days" />
              </el-select>
            </template>
            <template v-else>
              <el-time-picker
                v-model="form.timing.time"
                format="HH:mm"
                placeholder="选择时间"
              />
              <el-checkbox-group v-model="form.timing.days">
                <el-checkbox
                  v-for="day in weekDays"
                  :key="day.value"
                  :label="day.value"
                >
                  {{ day.label }}
                </el-checkbox>
              </el-checkbox-group>
            </template>
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="'active'"
            :inactive-value="'inactive'"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 提醒记录对话框 -->
    <el-dialog
      v-model="recordsDialogVisible"
      title="提醒记录"
      width="800px"
    >
      <el-table
        :data="reminderRecords"
        border
        v-loading="recordsLoading"
        style="width: 100%"
      >
        <el-table-column prop="messageTitle" label="消息标题" min-width="200" />
        <el-table-column prop="channel" label="提醒方式" width="120">
          <template #default="scope">
            <el-tag :type="getChannelType(scope.row.channel)">
              {{ getChannelLabel(scope.row.channel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getRecordStatusType(scope.row.status)">
              {{ getRecordStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="sendTime" label="发送时间" width="180" />
        <el-table-column prop="remark" label="备注" min-width="200" />
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="recordsPageNum"
          v-model:page-size="recordsPageSize"
          :total="recordsTotal"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleRecordsSizeChange"
          @current-change="handleRecordsCurrentChange"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Delete } from '@element-plus/icons-vue'
import {
  getReminderList,
  createReminder,
  updateReminder,
  deleteReminder,
  updateReminderStatus,
  getReminderRecords
} from '@/api/message'

// 搜索和筛选
const searchQuery = ref('')
const statusFilter = ref('')

// 数据加载状态
const loading = ref(false)
const submitting = ref(false)
const recordsLoading = ref(false)

// 分页数据
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 记录分页数据
const recordsPageNum = ref(1)
const recordsPageSize = ref(10)
const recordsTotal = ref(0)

// 列表数据
const reminderList = ref([])
const reminderRecords = ref([])

// 对话框显示状态
const dialogVisible = ref(false)
const recordsDialogVisible = ref(false)
const dialogType = ref('create')

// 表单引用
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: '',
  name: '',
  type: '',
  conditions: [{ field: '', operator: '', value: '' }],
  channels: [],
  timing: {
    type: 'immediate',
    delay: 30,
    unit: 'minutes',
    time: null,
    days: []
  },
  status: 'active',
  remark: ''
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择提醒类型', trigger: 'change' }],
  channels: [{ required: true, message: '请选择提醒方式', trigger: 'change' }]
}

// 提醒类型
const reminderTypes = [
  { value: 'message', label: '消息提醒' },
  { value: 'task', label: '任务提醒' },
  { value: 'system', label: '系统提醒' }
]

// 提醒方式
const reminderChannels = [
  { value: 'email', label: '邮件' },
  { value: 'sms', label: '短信' },
  { value: 'wechat', label: '微信' },
  { value: 'app', label: '应用内' }
]

// 条件字段
const conditionFields = [
  { value: 'type', label: '消息类型' },
  { value: 'status', label: '处理状态' },
  { value: 'priority', label: '优先级' },
  { value: 'category', label: '分类' }
]

// 操作符
const operators = [
  { value: 'eq', label: '等于' },
  { value: 'neq', label: '不等于' },
  { value: 'gt', label: '大于' },
  { value: 'lt', label: '小于' },
  { value: 'contains', label: '包含' }
]

// 星期选项
const weekDays = [
  { value: 1, label: '周一' },
  { value: 2, label: '周二' },
  { value: 3, label: '周三' },
  { value: 4, label: '周四' },
  { value: 5, label: '周五' },
  { value: 6, label: '周六' },
  { value: 7, label: '周日' }
]

// 初始化数据
onMounted(() => {
  fetchReminderList()
})

// 获取提醒规则列表
const fetchReminderList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      query: searchQuery.value,
      status: statusFilter.value
    }
    const res = await getReminderList(params)
    reminderList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取提醒规则列表失败:', error)
    ElMessage.error('获取提醒规则列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  pageNum.value = 1
  fetchReminderList()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchReminderList()
}

const handleCurrentChange = (val) => {
  pageNum.value = val
  fetchReminderList()
}

// 记录分页处理
const handleRecordsSizeChange = (val) => {
  recordsPageSize.value = val
  fetchReminderRecords()
}

const handleRecordsCurrentChange = (val) => {
  recordsPageNum.value = val
  fetchReminderRecords()
}

// 新建提醒规则
const handleCreate = () => {
  dialogType.value = 'create'
  Object.assign(form, {
    id: '',
    name: '',
    type: '',
    conditions: [{ field: '', operator: '', value: '' }],
    channels: [],
    timing: {
      type: 'immediate',
      delay: 30,
      unit: 'minutes',
      time: null,
      days: []
    },
    status: 'active',
    remark: ''
  })
  dialogVisible.value = true
}

// 编辑提醒规则
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 查看提醒记录
const handleViewRecords = async (row) => {
  recordsDialogVisible.value = true
  recordsPageNum.value = 1
  await fetchReminderRecords(row.id)
}

// 获取提醒记录
const fetchReminderRecords = async (reminderId) => {
  recordsLoading.value = true
  try {
    const params = {
      pageNum: recordsPageNum.value,
      pageSize: recordsPageSize.value,
      reminderId
    }
    const res = await getReminderRecords(params)
    reminderRecords.value = res.data.list
    recordsTotal.value = res.data.total
  } catch (error) {
    console.error('获取提醒记录失败:', error)
    ElMessage.error('获取提醒记录失败')
  } finally {
    recordsLoading.value = false
  }
}

// 删除提醒规则
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该提醒规则吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteReminder(row.id)
      ElMessage.success('删除成功')
      fetchReminderList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 更新提醒规则状态
const handleStatusChange = async (row) => {
  try {
    await updateReminderStatus(row.id, row.status)
    ElMessage.success('状态更新成功')
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
    row.status = row.status === 'active' ? 'inactive' : 'active'
  }
}

// 添加条件
const addCondition = () => {
  form.conditions.push({ field: '', operator: '', value: '' })
}

// 移除条件
const removeCondition = (index) => {
  form.conditions.splice(index, 1)
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    const data = {
      ...form,
      condition: JSON.stringify(form.conditions)
    }
    
    if (dialogType.value === 'create') {
      await createReminder(data)
      ElMessage.success('创建成功')
    } else {
      await updateReminder(data)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    fetchReminderList()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(error.message || '提交失败')
  } finally {
    submitting.value = false
  }
}

// 工具函数
const getReminderTypeTag = (type) => {
  const typeMap = {
    message: 'info',
    task: 'warning',
    system: 'success'
  }
  return typeMap[type] || ''
}

const getReminderTypeLabel = (type) => {
  const labelMap = {
    message: '消息提醒',
    task: '任务提醒',
    system: '系统提醒'
  }
  return labelMap[type] || type
}

const getChannelType = (channel) => {
  const typeMap = {
    email: 'success',
    sms: 'warning',
    wechat: 'primary',
    app: 'info'
  }
  return typeMap[channel] || ''
}

const getChannelLabel = (channel) => {
  const labelMap = {
    email: '邮件',
    sms: '短信',
    wechat: '微信',
    app: '应用内'
  }
  return labelMap[channel] || channel
}

const getRecordStatusType = (status) => {
  const typeMap = {
    success: 'success',
    failed: 'danger',
    pending: 'warning'
  }
  return typeMap[status] || ''
}

const getRecordStatusLabel = (status) => {
  const labelMap = {
    success: '成功',
    failed: '失败',
    pending: '待发送'
  }
  return labelMap[status] || status
}

const formatCondition = (condition) => {
  try {
    const conditions = JSON.parse(condition)
    return conditions.map(item => {
      const field = conditionFields.find(f => f.value === item.field)?.label
      const operator = operators.find(o => o.value === item.operator)?.label
      return `${field} ${operator} ${item.value}`
    }).join(' 且 ')
  } catch (error) {
    return condition
  }
}
</script>

<style lang="scss" scoped>
.message-reminder {
  padding: 20px;

  .reminder-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-left {
        display: flex;
        gap: 16px;
      }
    }

    .condition-text {
      color: #606266;
    }

    .channel-tag {
      margin-right: 8px;
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .condition-item {
    display: flex;
    gap: 8px;
    margin-bottom: 8px;
    align-items: center;
  }

  .timing-settings {
    margin-top: 16px;
    padding: 16px;
    background-color: #f5f7fa;
    border-radius: 4px;

    .el-checkbox-group {
      margin-top: 8px;
    }
  }
}
</style> 